import type { UserInfoRes } from "~/types/UserInfo";
export const useLoginStore = defineStore("login", () => {
  const userName = ref("");
  const passWord = ref("");

  async function doLogin(): Promise<Boolean> {
    const { data } = await useFetch<UserInfoRes>(
      "http://qa-api.hbfintech.com:11095/user/login",
      { method: "post", body: { username: userName, password: passWord } }
    );
    const code = data.value?.code;
    if (code === 20000) {
      const token = data.value?.data?.token;
      if (token === undefined) {
        return false;
      } else {
        xToken().setXToken(token)

      //   let days = 7;//7天后过期
      // let date = new Date();
      // date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
      //   const xtoken = useCookie('X-Token',{expires:date})
      //   xtoken.value=token


        // await $fetch('/api/cookies/set', {
        //   method: "post",
        //   body: {
        //     key: "X-Token",
        //     value: token,
        //   },
        // });
      }
    }
    return true;
  }


  //这个函数不再使用，换成使用useCookie
  async function getToken():Promise<String>{
    
    const headers = useRequestHeaders(['cookie']) //这里必须将浏览器的cookie传给服务器，服务器才能获取到cookie内容 https://nuxt.com.cn/docs/getting-started/data-fetching#%E5%B0%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AF%B7%E6%B1%82%E5%A4%B4%E4%BC%A0%E9%80%92%E5%88%B0-api
    const token=await $fetch('/api/cookies/get', {
      method: "post",
      headers,
      body: {
        key: "X-Token",
      },
    });
    if(token===undefined){
      return ""
    }
    return token
  }

  return { userName, passWord, doLogin,getToken };
});
